﻿using Microsoft.AspNet.Identity;
using Sino.CapacityCloud.Repositories.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using System.Security.Cryptography;
using Sino.WebApi.Framework.Abstractions.Cryptography;

namespace Sino.CapacityCloud.Services
{

    public class ApplicationSignInManager
        : SignInManager<ApplicationUser>
    {

        private readonly ICaptchasService _captchasService;
        private readonly ITokenGenerator _tokenGenerator;

        public ApplicationSignInManager(
            UserManager<ApplicationUser> userManager,
            IHttpContextAccessor contextAccessor,
            IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory,
            IOptions<IdentityOptions> optionsAccessor,
            ILogger<SignInManager<ApplicationUser>> logger,
            ICaptchasService captchasService, ITokenGenerator tokenGenerator)
            : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger)
        {
            this._captchasService = captchasService;
            this._tokenGenerator = tokenGenerator;
        }

        public virtual async Task<SignInResult> CaptchasSignInAsync(string phoneNumber, string captchas, bool isPersistent, bool lockoutOnFailure)
        {
            return await this.CaptchasSignInAsync(await this.UserManager.FindByPhoneNumberAsync(phoneNumber), captchas, isPersistent, lockoutOnFailure);
        }

        public virtual async Task<SignInResult> CaptchasSignInAsync(ApplicationUser user, string captchas, bool isPersistent, bool lockoutOnFailure)
        {
            return await this.DoSignIn(user, async () =>
            {
                return await this._captchasService.ValidateCaptchasAsync(user.PhoneNumber, captchas);
            }, isPersistent, lockoutOnFailure);
        }

        public virtual async Task<SignInResult> TokenbSignInAsync(string phoneNumber, string token, bool isPersistent, bool lockoutOnFailure)
        {
            return await this.TokenbSignInAsync(await this.UserManager.FindByPhoneNumberAsync(phoneNumber), token, isPersistent, lockoutOnFailure);
        }

        public virtual async Task<SignInResult> TokenbSignInAsync(ApplicationUser user, string token, bool isPersistent, bool lockoutOnFailure)
        {
            return await this.DoSignIn(user, async () =>
            {
                return await Task.FromResult(this._tokenGenerator.ValidateToken(token) && string.Equals(user.Token, token, StringComparison.Ordinal));
            }, isPersistent, lockoutOnFailure);
        }

        protected virtual async Task<SignInResult> DoSignIn(ApplicationUser user, Func<Task<bool>> checker, bool isPersistent, bool lockoutOnFailure)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            var error = await PreSignInCheck(user);
            if (error != null)
            {
                return error;
            }
            if (await IsLockedOut(user))
            {
                return await LockedOut(user);
            }

            if (await checker())
            {
                await ResetLockout(user);
                await this.SignInAsync(user, isPersistent);
                return SignInResult.Success;
            }
            Logger.LogWarning(2, "User {userId} failed to provide the correct password.", await UserManager.GetUserIdAsync(user));

            if (UserManager.SupportsUserLockout && lockoutOnFailure)
            {
                // If lockout is requested, increment access failed count which might lock out the user
                await UserManager.AccessFailedAsync(user);
                if (await UserManager.IsLockedOutAsync(user))
                {
                    return await LockedOut(user);
                }
            }
            return SignInResult.Failed;
        }

        #region Utilities
        // TODO: Use relection to call the private functions defined in the base class.
        protected async Task<bool> IsLockedOut(ApplicationUser user)
        {
            return UserManager.SupportsUserLockout && await UserManager.IsLockedOutAsync(user);
        }

        protected async Task<SignInResult> LockedOut(ApplicationUser user)
        {
            Logger.LogWarning(3, "User {userId} is currently locked out.", await UserManager.GetUserIdAsync(user));
            return SignInResult.LockedOut;
        }

        protected async Task<SignInResult> PreSignInCheck(ApplicationUser user)
        {
            if (!await CanSignInAsync(user))
            {
                return SignInResult.NotAllowed;
            }
            if (await IsLockedOut(user))
            {
                return await LockedOut(user);
            }
            return null;
        }

        protected Task ResetLockout(ApplicationUser user)
        {
            if (UserManager.SupportsUserLockout)
            {
                return UserManager.ResetAccessFailedCountAsync(user);
            }
            return Task.FromResult(0);
        }
        #endregion

    }

}